<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%@ page import="java.lang.Runtime"%>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = "/home/wyg/lly/downfile/";
String filename="";

String test="test";

// 验证上传内容了类型
String contentType = request.getContentType();
//  if ((contentType.indexOf("multipart/form-data") >= 0))  {


DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存中存储文件的最大值
factory.setSizeThreshold(maxMemSize);
// 本地存储的数据大于 maxMemSize.
factory.setRepository(new File("/home/wyg/lly/downfile/"));

// 创建一个新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大上传的文件大小
upload.setSizeMax( maxFileSize );
try{ 
// 解析获取的文件
List fileItems = upload.parseRequest(request);

// 处理上传的文件
Iterator i = fileItems.iterator();


out.println("<html>");
out.println("<head>");
out.println("<title>burling</title>");  
out.println("</head>");
out.println("<body>");

//  while ( i.hasNext () ) 
//  {
//   i.hasNext();
FileItem fi = (FileItem)i.next();

if ( !fi.isFormField () )	
{
// 获取上传文件的参数

String fieldName = fi.getFieldName();
String fileName = fi.getName();
filename = fileName;
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// 写入文件

/*
if( fileName.lastIndexOf("\\") >= 0 ){
filename=fileName.substring( fileName.lastIndexOf("\\")) ;
file = new File( filePath , filename);

}else{

fileName.substring( fileName.lastIndexOf("\\")+1) ;
file = new File( filePath ,filename);

}
*/

file = new File("/home/wyg/lly/downfile/",fileName);
fi.write( file ) ;

//  out.println("Uploaded Filename: " + filePath +  fileName + "<br>");
}
//  }


out.println("</body>");
out.println("</html>");
response.addCookie(new Cookie("filename",filename));
response.sendRedirect("selectnodes.jsp");


//***************************************************

// String cmd1=" tos-bsl --telosb -c /dev/ttyUSB0 -r -e -I -p ";
// String cmd2=cmd1+filePath;
//  String cmd3=cmd2+filename;
// out.println(cmd3);

//	Process process = java.lang.Runtime.getRuntime().exec(cmd3);
//	int flag;
//flag=process.waitFor();
//if(0 == flag)
//{
out.println("SUCCESS!");
//}else
//{
//	out.println("FAIL!");
//}
}catch(Exception ex) {
System.out.println(ex);
out.println("WRITE ERROR");

out.println("</body>");
out.println("</html>");
}
//  }else{
/*
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");  
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>"); 
out.println("</body>");
out.println("</html>");
*/
//  }
%>
